package com.miyu.system.service.opensystem.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.miyu.common.pojo.WebServicePJ;
import com.miyu.common.utils.comservice.WebHttpService;
import com.miyu.common.utils.ehcache.EhcacheUtil;
import com.miyu.system.dao.system.SysCityDao;
import com.miyu.system.service.opensystem.OpenSystemService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;


/**
 * 开放系统服务impl
 *
 * @author longm
 * @date 2022/09/29
 */
@Service
public class OpenSystemServiceImpl implements OpenSystemService {

    @Resource
    private SysCityDao sysCityDao;
    @Override
    @Cacheable(cacheNames  = "system:weather#3600",key="#param.getString('vCity')")
    public JSONObject getWeather(JSONObject param) throws Exception {
        String key = param.getString("vCity");
        String version ="";
        version=param.getString("version");
        String city = param.getString("city");
        JSONObject rs = new JSONObject();
        //数据进行缓存 校验数据是否有 如果有是否超过两小时 如果超过一个小时更新 否者直接取值返回不再更新时间
        StringBuffer url = new StringBuffer();
        url.append("https://www.tianqiapi.com/api?");
        url.append("unescape=1");
        url.append("&version=").append(version);
        url.append("&appid=16319171&appsecret=Ywlwceu5");
        url.append("&cityid=").append(city);
        if(EhcacheUtil.getInstance().hasKey("weather",key)){
            rs = (JSONObject) EhcacheUtil.getInstance().get("weather",key );
        }else {
            // 返回结果字符串
            String result = null;
            WebServicePJ pj = new WebServicePJ();
            pj.setUrl(url.toString());
            pj.setMethod("GET");
            result = WebHttpService.getWebHttpServiceStr(pj);
            if(result.length()>0) {
                rs = JSONObject.parseObject(result);
            }
            EhcacheUtil.getInstance().put("weather",key ,rs,3600);
        }
        return rs;
    }

    /**
     * 查询系统城市
     *
     * @return {@link JSONArray}
     */
    @Override
    @Cacheable(cacheNames="system:sysCity" ,key="'sysCity'")
    public JSONArray querySysCity() {
        return JSONArray.parseArray(JSONArray.toJSONString(sysCityDao.findAll()), JSONReader.Feature.IgnoreSetNullValue) ;
    }
}
